import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/common/theme/app_colors.dart';
import 'package:flutter_taotaoshipin/util/image_utils.dart';
import 'package:flutter_taotaoshipin/util/theme_utils.dart';
import 'package:flutter_taotaoshipin/value/constant.dart';
import 'package:flutter_taotaoshipin/widget/load_image.dart';
import 'package:get/get.dart';

import 'drama_episode_controller.dart';

class DramaEpisodePage extends StatefulWidget {
  const DramaEpisodePage({Key? key}) : super(key: key);

  @override
  State<DramaEpisodePage> createState() => _DramaEpisodePageState();
}

class _DramaEpisodePageState extends State<DramaEpisodePage> {
  final controller = Get.find<DramaEpisodeController>();
  final state = Get.find<DramaEpisodeController>().state;

  @override
  void dispose() {
    Get.delete<DramaEpisodeController>();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double bottom = context.mediaQueryPadding.bottom;
    return Container(
      decoration: BoxDecoration(
        borderRadius: const BorderRadius.vertical(top: Radius.circular(15)),
        color: Colors.white,
      ),
      child: CustomScrollView(
        slivers: [
          SliverPersistentHeader(
            pinned: true,
            delegate: _SliverPersistentHeaderDelegate(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.fromLTRB(20, 17, 20, 0),
                    child: Row(
                      children: [
                        Text(
                          controller.mainInfoEntity?.title ?? '',
                          style: const TextStyle(
                            color: Color(0xFF2D2D2D),
                            fontSize: 16,
                            fontWeight: FontWeight.w900,
                          ),
                        ),
                        SizedBox(width: 8),
                        Text(
                          '（全${controller.mainInfoEntity?.allEp ?? 0}集）',
                          style: const TextStyle(
                            fontSize: 12,
                            color: AppColors.text_gray,
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(height: 15),
                  Divider(indent: 16, endIndent: 16),
                  SizedBox(height: 15),
                  GetBuilder<DramaEpisodeController>(
                      builder: (controller) {
                    return Container(
                      width: double.infinity,
                      height: 20,
                      child: ListView.separated(
                        scrollDirection: Axis.horizontal,
                        itemBuilder: (_, index) {
                          var model = state.tabTitles[index];
                          return GestureDetector(
                            onTap: () {
                              controller.xuanjiItemClicked(index);
                            },
                            child: Container(
                              padding: EdgeInsets.symmetric(horizontal: 20),
                              alignment: Alignment.center,
                              child: Text(
                                model,
                                style: TextStyle(
                                  color: state.selectedTabIndex ==
                                          index
                                      ? AppColors.app_main
                                      : Color(0xFF2D2D2D),
                                  fontSize: 14,
                                  fontWeight:
                                      state.selectedTabIndex ==
                                              index
                                          ? FontWeight.bold
                                          : FontWeight.normal,
                                ),
                              ),
                            ),
                          );
                        },
                        separatorBuilder: (_, index) {
                          return VerticalDivider(
                            color: Color(0xFFB4B3B8).withOpacity(0.2),
                            indent: 2,
                            endIndent: 2,
                          );
                        },
                        itemCount: state.tabTitles.length,
                      ),
                    );
                  }),
                  SizedBox(height: 15),
                ],
              ),
            ),
          ),
          SliverFillRemaining(
            child: GridView.builder(
              controller: controller.scrollController,
              padding: EdgeInsets.fromLTRB(15, 0, 15, 0 + bottom),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 6,
                mainAxisSpacing: 10,
                crossAxisSpacing: 10,
                childAspectRatio: 1,
              ),
              itemCount: Constant.isFree
                  ? controller.userDramaAuthListEntityList.length
                  : controller.dramaListEntityList.length,
              itemBuilder: (ctx, index) {
                var model = controller.dramaListEntityList[index];
                var unlock = controller.userDramaAuthListEntityList
                        .indexWhere((element) => element.id == model.id) >
                    -1;
                return _buildItem(
                  sort: model.sort!,
                  unlock: unlock,
                  isPlaying: controller.isPlayingSort == model.sort,
                  onTap: () {
                    Get.back(result: {'index': index, 'sort': model.sort});
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  _buildItem({
    required int sort,
    bool unlock = false,
    bool isPlaying = false,
    VoidCallback? onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        decoration: BoxDecoration(
          color: Color(0xFFF6F6F6),
          borderRadius: BorderRadius.circular(6),
          border: isPlaying
              ? Border.all(color: AppColors.app_main)
              : null,
        ),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Text(
              '$sort',
              style: TextStyle(
                color: isPlaying
                    ? AppColors.app_main
                    : Color(0xFF2D2D2D),
                fontSize: 17,
                fontWeight: FontWeight.bold,
              ),
            ),
            if (!unlock)
              Positioned(
                left: 4,
                top: 4,
                child: LoadAssetImage(
                  'drama/episode/lock',
                  width: 10,
                ),
              ),
            if (isPlaying)
              Positioned(
                right: 4,
                bottom: 4,
                child: LoadAssetImage(
                  'drama/episode/playing',
                  width: 9,
                  format: ImageFormat.gif,
                ),
              ),
          ],
        ),
      ),
    );
  }
}

class _SliverPersistentHeaderDelegate
    extends SliverPersistentHeaderDelegate {
  _SliverPersistentHeaderDelegate({required this.child});

  final Widget child;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return child;
  }

  @override
  // TODO: implement maxExtent
  double get maxExtent => 105;

  @override
  // TODO: implement minExtent
  double get minExtent => 105;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}
